package com.comtime.service;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlarmManager;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.location.AMapLocationListener;
import com.comtime.entity.FirmwareInfo;
import com.comtime.entity.MusicInfo;
import com.comtime.entity.UserInfo;
import com.comtime.greendaodemo.DeviceInfo;
import com.comtime.greendaodemo.OpenLockInfo;
import com.comtime.greendaodemo.RemindInfo;
import com.comtime.greendaoutils.DataBaseUtil;
import com.comtime.login.LoginActivity;
import com.comtime.manager.SKNotificationManager;
import com.comtime.manager.SwDeviceNew;
import com.comtime.mybox.AddFringerActivity;
import com.comtime.mybox.FingerprintManagerActivity;
import com.comtime.mybox.OADActivity;
import com.comtime.smartbox.Activity_0;
import com.comtime.smartbox.HBApplication;
import com.comtime.smartbox.MainActivity;
import com.comtime.smartkilimanjaro.R;
import com.comtime.swdevice.Conversion;
import com.comtime.swdevice.DeviceListener;
import com.comtime.swdevice.DeviceScanCallBack;
import com.comtime.swdevice.SWDevice;
import com.comtime.swdevice.SWDeviceScanManager;
import com.comtime.utils.LogUtils;
import com.comtime.utils.MusicPlayer;
import com.comtime.utils.MyConfig;
import com.comtime.utils.MySharedPreferences;
import com.comtime.utils.ToastUtils;
import com.comtime.utils.Util;
import com.comyou.comyouhttp.ComyouHttpCallBack;
import com.comyou.comyouhttp.ComyouHttpClient;
import com.comyou.comyouhttp.ComyouHttpProgram;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

public class MyService extends Service implements DeviceListener {

    private String TAG = "MyService";

    boolean isSamsung = false;
    HBApplication application;

    // lanya
    SWDeviceScanManager scanManager = null;
    BluetoothManager bluetoothManager;
    BluetoothAdapter bluetoothAdapter = null;

    public static String ACTION_MYSERVICE = "com.comtime.smartbox.myservice";

    // 设备连接
    public static String ACTION_CONNECTED = "com.comtime.smartbox.ACTION_CONNECTED";
    // 设备断开
    public static String ACTION_DISCONNECTED = "com.comtime.smartbox.ACTION_DISCONNECTED";

    public static String ACTION_OADProgress = "com.comtime.smartbox.ACTION_OADProgress";
    public static String EXTRA_OADProgress = "com.comtime.smartbox.EXTRA_OADProgress";
    public static String EXTRA_OADTimeLeft = "com.comtime.smartbox.EXTRA_OADTimeLeft";

    public static String ACTION_ShowOAD = "com.comtime.smartbox.ACTION_ShowOAD";
    public static String ACTION_UpdateOADState = "com.comtime.smartbox.ACTION_UpdateOADState";
    public static String ACTION_UpdateDeviceName = "com.comtime.smartbox.ACTION_UpdateDeviceName";

    // 系统蓝牙连接变化
    public static String ACTION_BLUTOOTH_CHANGE = "com.comtime.smartbox.ACTION_BLUTOOTH_CHANGE";
    // 电池信息
    public static String ACTION_BATTERYVALUE = "com.comtime.smartbox.ACTION_BATTERYVALUE";
    // 低电池信息
    public static String ACTION_LOW_BATTERYVALUE = "com.comtime.smartbox.ACTION_LOW_BATTERYVALUE";
    // 删除设备
    public static String ACTION_REMOVEDEVICE = "com.comtime.smartbox.ACTION_REMOVEDEVICE";
    // 网络连接变化
    public final static String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
    // 主界面UI界面变化
    public static String ACTION_HOME_UI_CHANGE = "com.comtime.smartbox.ACTION_HOME_UI_CHANGE";
    // main界面设备列表变化
    public static String ACTION_MAIN_DEVICEUI_CHANGE = "com.comtime.smartbox.ACTION_MAIN_DEVICEUI_CHANGE";
    // 换设备
    public static String ACTION_UPDATE_UI = "com.comtime.smartbox.update_choice_ui";
    // 验证用户结果
    public static String ACTION_CHECKUSER_RESULT = "com.comtime.smartbox.checkuser_result";
    // 验证管理员密码结果
    public static String ACTION_CHECKADMINEPWD_RESULT = "com.comtime.smartbox.adminepwd_check_result";
    // 验证管理员密码修改结果
    public static String ACTION_ADMINEPWD_UPDATE_RESULT = "com.comtime.smartbox.adminepwd_update_result";
    // 查询箱包所有用户结果
    public static String ACTION_CHECK_ALLUSER_RESULT = "com.comtime.smartbox.check_alluser_result";
    // 添加箱包用户结果
    public static String ACTION_ADD_USER_RESULT = "com.comtime.smartbox.add_user_result";
    // 删除箱包用户结果
    public static String ACTION_DELETE_USER_RESULT = "com.comtime.smartbox.delete_user_result";
    // 箱包第一次添加用户
    public static String ACTION_FIST_ADDUSER = "com.comtime.smartbox.first_adduser";


    // 获取到开锁记录
    public static String ACTION_Get_OpenLockInfo = "com.comtime.smartbox.ACTION_Get_OpenLockInfo";
    public static String Extra_OpenLockInfo = "com.comtime.smartbox.Extra_Get_OpenLockInfo";


    public static String SELECT_TAG = "SELECT_TAG";//
    public static String VALUE_TAG = "VALUE_TAG";

    public static String VALUE_INFO = "VALUE_INFO";// 信息


    /**
     * 系统提醒广播
     */
    AlarmManager aManager;
    MusicPlayer musicPlayer;
    WakeLock wakeLock;

    DataBaseUtil dataBaseUtil;
    private final IBinder binder = new LocalBinder();

    @Override
    public IBinder onBind(Intent arg0) {
        return binder;
    }

    public class LocalBinder extends Binder {

        public MyService getService() {
            Log.i("tag", "1:1");
            return MyService.this;
        }
    }

    /**
     * 高德定位
     */
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        application = (HBApplication) getApplication();
        addListMySharedPreferences();
        aManager = (AlarmManager) getSystemService(Service.ALARM_SERVICE);
        Log.i("tag", " service onCreate");
        if (!getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_BLUETOOTH_LE)) {
            MyConfig.canUse = false;
            return;
        } else {
            MyConfig.canUse = true;
        }
        dataBaseUtil = DataBaseUtil.getInstance(this);
        musicPlayer = new MusicPlayer(this);
        isSamsung = Util.CheckIsSamsung();
        initRunnables();
        openBlueTooth();

        application.swDevicesList = new ArrayList<SwDeviceNew>();
        if (application.swDevicesList.size() == 0) {
            for (int i = 0; i < 1; i++) {
                SwDeviceNew device = new SwDeviceNew(this, i);
                device.setDeviceListener(this);
                // 初始配置
                device.musicPlayer = new MusicPlayer(MyService.this);
                application.swDevicesList.add(device);
            }
        }
        List<DeviceInfo> deviceInfos = dataBaseUtil
                .loadDeviceInfo(mySharedPreferences.getPhoneNum());
        if (!mySharedPreferences.getBluAdress().equals("")) {

            if (deviceInfos != null && deviceInfos.size() > 0) {
                boolean b_has = false;
                for (int i = 0; i < deviceInfos.size(); i++) {
                    String mac = deviceInfos.get(i).getMac();
                    if (mySharedPreferences.getBluAdress().equals(mac)) {
                        b_has = true;
                        break;
                    }
                }
                if (!b_has) {
                    mySharedPreferences.saveBluAdress(deviceInfos.get(0)
                            .getMac());
                }
            }

        } else {
            if (deviceInfos != null && deviceInfos.size() > 0) {
                mySharedPreferences.saveBluAdress(deviceInfos.get(0).getMac());
            }
        }
        if (!mySharedPreferences.getBluAdress().equals("")) {
            scanManager.startScan();
        }
        sendBroadcast(new Intent(ACTION_HOME_UI_CHANGE));

        // 解决新装软件完成之后 直接点击打开 ，然后退到后台，点击图片再次进入会从welcome开始 （页面假杀死）的问题
        if (Util.isAppOnForeground(this)) {

            Intent intent = new Intent(this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                    | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);//
            startActivity(intent);
        }

        // 防止后台服务暂停
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                MyService.class.getName());
        wakeLock.acquire();
        regist();
        // 高德
        locationClient = new AMapLocationClient(this.getApplicationContext());
        locationOption = new AMapLocationClientOption();
        initGaoDeOption();

		/*handler.postDelayed(upOpenLockInfoRunnable, 5 * 1000);
        handler.postDelayed(upRemindInfoRunnable, 10 * 1000);
		handler.postDelayed(deleteLockinfoRunnable, 15 * 1000);
		handler.postDelayed(deleteRemindInfoRunnable, 20 * 1000);*/
        MusicInfo musicInfo = null;
        String lowPowerpath = "android.resource://" + getPackageName()
                + "/" + R.raw.lowpower;
        musicInfo = new MusicInfo(lowPowerpath);
        mySharedPreferences.saveLostDeviceWainVoicePath(lowPowerpath);
        String lostPath = "android.resource://" + getPackageName()
                + "/" + R.raw.lost;
        musicInfo = new MusicInfo(lostPath);
        mySharedPreferences.saveLostDeviceWainVoicePath(lostPath);

    }

    void regist() {
        IntentFilter intentFilter = new IntentFilter(ACTION_MYSERVICE);
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        intentFilter.addAction(CONNECTIVITY_CHANGE_ACTION);
        registerReceiver(receiver, intentFilter);
    }

    /**
     * 启动蓝牙
     */
    void openBlueTooth() {

        bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        if (bluetoothAdapter == null) {
            bluetoothAdapter = bluetoothManager.getAdapter();
        }

        if (!bluetoothAdapter.isEnabled()) {
            bluetoothAdapter.enable();
            MyConfig.bluetoothEnabled = bluetoothAdapter.isEnabled();
            sendBroadcast(new Intent(ACTION_BLUTOOTH_CHANGE));
        }
        if (scanManager == null) {
            scanManager = new SWDeviceScanManager(this);
            scanManager.setScanCallBack(callBack);
        }

    }

    /**
     * 配置文件
     */
    MySharedPreferences mySharedPreferences;

    void addListMySharedPreferences() {
        mySharedPreferences = MySharedPreferences.getInstance(this);
    }

    /**
     * update ui
     *
     * @param j
     */

    void updateFist(int j) {
        Intent fistIntent = new Intent(MyService.ACTION_UPDATE_UI);
        fistIntent.putExtra(SELECT_TAG, j);
        sendBroadcast(fistIntent);
    }

    // 发送定位请求
    private long locationInterval = 20 * 1000;

    private void initGaoDeOption() {
        // 设置定位模式为高精度模式
        locationOption.setLocationMode(AMapLocationMode.Hight_Accuracy);
        // 设置定位监听
        locationClient.setLocationListener(aMapLocationListener);
        locationOption.setOnceLocation(false);
        // 设置是否需要显示地址信息
        locationOption.setNeedAddress(true);
        /**
         * 设置是否优先返回GPS定位结果，如果30秒内GPS没有返回定位结果则进行网络定位 注意：只有在高精度模式下的单次定位有效，其他方式无效
         */
        locationOption.setGpsFirst(false);
        // 设置发送定位请求的时间间隔,最小值为1000，如果小于1000，按照1000算
        locationOption.setInterval(locationInterval);
        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        // 启动定位
        locationClient.startLocation();
    }

    /**
     * scan result
     */
    List<BluetoothDevice> devicelist = new ArrayList<BluetoothDevice>();
    private DeviceScanCallBack callBack = new DeviceScanCallBack() {
        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] arg2) {

            String address = device.getAddress().replace(":", "").toUpperCase();
            // Log.e("tag", "onLeScan 1 " + address);
            if (rssi > -80
                    && address.equals(mySharedPreferences.getBluAdress())) {
                scanManager.stopScan();
                BluetoothDevice device2 = scanManager
                        .retrieveBluetoothDeviceWithMac(device.getAddress());
                application.swDevicesList.get(0).setBluetoothDevice(device2);
                handler.removeCallbacks(connectRunnable);
                handler.postDelayed(connectRunnable, 500);
            }
        }
    };

    private Runnable connectRunnable = new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            application.swDevicesList.get(0).connectGatt();
        }
    };

    private double Longitude = 0, Latitude = 0;
    private String mapAddress = "";
    AMapLocationListener aMapLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    Longitude = aMapLocation.getLongitude();
                    Latitude = aMapLocation.getLatitude();
                    mapAddress = aMapLocation.getAddress();
                } else {
                    Longitude = 0;
                    Latitude = 0;
                    mapAddress = "";
                }
                Log.i("tag", "Longitude:" + Longitude + " Latitude:" + Latitude
                        + " mapAddress:" + mapAddress);
            }
        }
    };

    @Override
    public void onConnected(final int tag, BluetoothDevice device) {
        Log.e("tag", "connected：" + tag);
        application.swDevicesList.get(tag).musicPlayer.stopPlay();
        handler.removeCallbacks(batteryReadRunnable);

        final String address = device.getAddress().replace(":", "")
                .toUpperCase();
        mySharedPreferences.saveBluAdress(address);
        scanManager.stopScan();

        Intent intent = new Intent(ACTION_CONNECTED);
        intent.putExtra(SELECT_TAG, tag);
        sendBroadcast(intent);
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                boolean needAuth = mySharedPreferences.getBoolen("needAuth");
                if (needAuth) {
                    Log.e("needAuth", "" + needAuth);
                    String adminPWD = "888888";
                    sendAuthValue(tag, address, adminPWD);
                } else {
                    application.swDevicesList.get(tag).checkUserPhone(
                            mySharedPreferences.getPhoneNum());
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    application.swDevicesList.get(tag).readBattery();
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    if (application.swDevicesList.get(tag).isOADing) {
                        application.swDevicesList.get(tag).startOADMode();
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }

                }


            }
        }).start();

        // 添加提醒
        RemindInfo info = new RemindInfo();
        info.setAddress(mapAddress);
        info.setMacAddress(address);
        info.setStyle(1);
        info.setUpflag(1);
        info.setUser_id(mySharedPreferences.getUserId());
        info.setTime(Util.formatTimeStyle_4(System.currentTimeMillis()));
        info.setLat(Latitude);
        info.setLng(Longitude);
        dataBaseUtil.saveRemindInfo(info);

        startSendSettings(tag);

    }

    private void sendAuthValue(int tag, String macAddress, String adminPWD) {
        // ---values:07080F383838383838987BF3613495
        byte[] values = new byte[15];
        values[0] = 0x07;
        values[1] = 0x08;
        values[2] = 15;
        byte[] pwd = adminPWD.getBytes();
        LogUtils.e(TAG, " 888888  length:" + pwd.length);
        for (int i = 3; i < 9; i++) {
            values[i] = pwd[i - 3];
        }

        byte[] macValue = Conversion.hexStringToBytes(macAddress);

        // MAC地址倒过来
        for (int i = 9; i < (9 + macValue.length); i++) {
            values[i] = macValue[15 - i - 1];
        }

        LogUtils.e(TAG, " ---values:" + Conversion.Bytes2HexString(values));
        application.swDevicesList.get(tag).sendToDevice(values);

    }

    @Override
    public void onDisconnected(int tag, BluetoothDevice device) {
        Log.e("tag", "disConnected：" + tag);
        application.swDevicesList.get(tag).checkUserOk = false;
        stopSendSettings(tag);
        Intent intent = new Intent(ACTION_DISCONNECTED);
        intent.putExtra(SELECT_TAG, tag);
        sendBroadcast(intent);

        if (!mySharedPreferences.getBluAdress().equals("")
                && MyConfig.bluetoothEnabled) {
            scanManager.startScan();
        }
        if (!application.swDevicesList.get(tag).isChecking
                && application.swDevicesList.get(tag).getBluetoothDevice() != null
                && !application.swDevicesList.get(tag).isOADing) {

            checkWain(tag);

        }
    }

    @Override
    public void onConn(int tag, BluetoothDevice device) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onGetBattery(int tag, int battery, BluetoothDevice device) {

        Log.e("tag", "tag:" + tag + " battery:" + battery);
        long time = System.currentTimeMillis();
        long lastTime = mySharedPreferences.getLowBatteryLastTime();
        application.swDevicesList.get(tag).battery = battery;
        if (battery < 10 && (time - lastTime) / 1000 - 3 * 60 > 0) {
            // 添加低电量提醒,三分钟内触发一次
            RemindInfo info = new RemindInfo();
            info.setMacAddress(mySharedPreferences.getBluAdress());
            info.setStyle(3);
            info.setUpflag(1);
            info.setTime(Util.formatTimeStyle_4(System.currentTimeMillis()));
            info.setUser_id(mySharedPreferences.getUserId());
            dataBaseUtil.saveRemindInfo(info);
            Intent intent = new Intent(ACTION_LOW_BATTERYVALUE);
            intent.putExtra(SELECT_TAG, tag);
            sendBroadcast(intent);

            mySharedPreferences.saveLowBatteryLastTime(time);

            if (mySharedPreferences.getLowBatteryWain()) {
                MusicInfo musicInfo = null;
                String path = "android.resource://" + getPackageName()
                        + "/" + R.raw.lowpower;
                musicInfo = new MusicInfo(path);
                MusicPlayer  musicPlayer=new MusicPlayer(this);
                musicPlayer.playWithPath(path);
                application.swDevicesList.get(tag).musicPlayer
                        .playWithTimesAndPath(mySharedPreferences
                                        .getLowBatteryWainTimes(),mySharedPreferences.getLowBatteryWainVoicePath(),
                                mySharedPreferences.getLowBatteryVibrate(),
                                true);
            }
        }
        mySharedPreferences.saveBattery(battery);
        Intent intent = new Intent(ACTION_BATTERYVALUE);
        intent.putExtra(SELECT_TAG, tag);
        sendBroadcast(intent);

    }

    @Override
    public void onGetRssi(int tag, int rssi, BluetoothDevice device) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onGetValue(int tag, int value, BluetoothDevice device) {
        Log.i("tag", "device" + tag + "  value:" + value);
        switch (value) {
            case SWDevice.COMMAND_FINDING_PHONE:

                Log.i("tag", "device" + tag + " is finding your phone");
                doValue(11, tag);
                break;
            case SWDevice.COMMAND_STOP_FINDING_PHONE:
                doValue(10, tag);
                Log.i("tag", "device" + tag + " stop find your phone");
                break;
            case SWDevice.COMMAND_FULL_BATTERY:
                doValue(73, tag);
                Log.i("tag", "device" + tag + " is fully charged");
                break;
            case SWDevice.COMMAND_LOW_BATTERY:
                doValue(71, tag);
                Log.i("tag", "device" + tag + " is low battery");
                break;
            case 0x71://疑似低电量
                doValue(71, tag);
                break;
            case SWDevice.COMMAND_NULL_BATTERY:
                doValue(72, tag);
                Log.i("tag", "device" + tag + " is power off");
                break;
            case SWDevice.COMMAND_REMIND_TICK:
                Log.i("tag", "device" + tag + " reminder tick");
                break;
            case 60:
                application.swDevicesList.get(tag).sendToDevice(6);
                break;
            case 61:
                break;
            default:
                break;
        }
    }

    @Override
    public void onSendSuccess(int tag, int value, BluetoothDevice device) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onGetImageVerAndType(final int tag, int ver, char type,
                                     BluetoothDevice device) {
        // TODO Auto-generated method stub

        application.swDevicesList.get(tag).versionChar = type;

        application.swDevicesList.get(tag).versionCode = ver;
        if (application.swDevicesList.get(tag).isOADing) {
            return;
        }
        handler.post(new Runnable() {

            @Override
            public void run() {
                checkNeedUpdate(tag);
            }
        });

    }

    @Override
    public void onGetDeviceName(final int tag, String deviceName,
                                BluetoothDevice device) {
        Log.e("tag", "deviceName:" + deviceName);
        application.swDevicesList.get(tag).versionName = deviceName;

        Intent intent = new Intent(ACTION_UpdateDeviceName);
        sendBroadcast(intent);
        if (application.swDevicesList.get(tag).isOADing) {
            return;
        }
        handler.post(new Runnable() {

            @Override
            public void run() {
                checkNeedUpdate(tag);
            }
        });

    }

    private void checkNeedUpdate(final int tag) {
        // int delta = (application.swDevicesList.get(tag).versionChar == 'A') ?
        // 3
        // : 2;
        // localImageA=5000; //测试OAD代码，发布必删
        // localImageB=5000;//测试OAD代码，发布必删

		/*
         * if (application.swDevicesList.get(tag).versionChar == 'A') { if
		 * (localImageA > application.swDevicesList.get(tag).versionCode) {
		 * Log.e(TAG, " device 0 need OAD");
		 * application.swDevicesList.get(tag).needOAD = true; } else {
		 * application.swDevicesList.get(tag).needOAD = false; } } else if
		 * (application.swDevicesList.get(tag).versionChar == 'B') {//4619 B if
		 * (localImageB > application.swDevicesList.get(tag).versionCode) {
		 * Log.e(TAG, " device 0 need OAD");
		 * application.swDevicesList.get(tag).needOAD = true; } else {
		 * application.swDevicesList.get(tag).needOAD = false; } }
		 */
        // if (localImageA > application.swDevicesList.get(tag).versionCode
        // + delta) {
        // Log.e(TAG, " device 0 need OAD");
        // application.swDevicesList.get(tag).needOAD = true;
        // } else {
        // Log.e(TAG, " device 0 don't need OAD");
        // application.swDevicesList.get(tag).needOAD = false;
        // }

        if (application.swDevicesList.get(tag).versionCode > 0
                && application.swDevicesList.get(tag).versionName.length() > 0) {
            // 版本名称和版本信息都读取成功的情况下， 请求服务器 最新固件信息，来对比是否需要升级

            ComyouHttpProgram httpProgram = new ComyouHttpProgram();
            httpProgram.add("type", "1"); // 检测固件更新
            LogUtils.e("tag", " httpProgram:"
                    + httpProgram.getPrograms().toString());

            ComyouHttpClient httpClient = new ComyouHttpClient(
                    MyConfig.Check_Update_IP);
            httpClient.postAsync(httpProgram, new ComyouHttpCallBack() {

                @Override
                public void onResponse(final String string) {
                    LogUtils.e("tag", "Check_Update：" + string);
                    try {
                        JSONObject jsonObject = new JSONObject(string);
                        int err = jsonObject.getInt("err");
                        if (err == 0) {

                            JSONArray array = jsonObject.getJSONArray("data");
                            if (array.length() == 2) {
                                FirmwareInfo firmwareInfoA = new FirmwareInfo();
                                JSONObject objectA = (JSONObject) array.get(0);
                                String urlA = objectA.getString("file");
                                if (!urlA.startsWith("http://")) {
                                    urlA = "http://" + urlA;
                                }
                                firmwareInfoA.fileURL = urlA;
                                firmwareInfoA.version = (float) objectA
                                        .getDouble("version");

                                FirmwareInfo firmwareInfoB = new FirmwareInfo();
                                JSONObject objectB = (JSONObject) array.get(1);
                                String urlB = objectB.getString("file");
                                if (!urlB.startsWith("http://")) {
                                    urlB = "http://" + urlB;
                                }
                                firmwareInfoB.fileURL = urlB;
                                firmwareInfoB.version = (float) objectB
                                        .getDouble("version");

                                double code = Double
                                        .valueOf(application.swDevicesList
                                                .get(tag).versionName
                                                .split("V")[1]);

                                if (firmwareInfoA.version > code) {
                                    application.swDevicesList.get(tag).needOAD = true;
                                } else {
                                    application.swDevicesList.get(tag).needOAD = false;
                                }

                                if (application.swDevicesList.get(tag).needOAD) {
                                    downloadFirmware(firmwareInfoA,
                                            firmwareInfoB);
                                }
                            }

                        }

                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(String arg0, IOException arg1) {

                }
            });

        }

    }

    boolean successA;
    boolean successB;

    protected void downloadFirmware(FirmwareInfo firmwareInfoA,
                                    FirmwareInfo firmwareInfoB) {
        HttpUtils http = new HttpUtils();
        final String filePathA = Util.getFirmwarePath(firmwareInfoA.version)
                + "/ImageA.bin";
        final String filePathB = Util.getFirmwarePath(firmwareInfoB.version)
                + "/ImageB.bin";

        successA = false;
        successB = false;
        http.download(firmwareInfoA.fileURL, filePathA,
                new RequestCallBack<File>() {

                    @Override
                    public void onSuccess(ResponseInfo<File> responseInfo) {
                        // TODO Auto-generated method stub
                        LogUtils.e(
                                TAG,
                                "A responseInfo:"
                                        + responseInfo.result.getAbsolutePath());
                        successA = true;
                        mySharedPreferences.saveImageAFilePath(filePathA);
                        if (successA && successB) {

                            if (mySharedPreferences.getNeedShowOADCaution()) {
                                mySharedPreferences
                                        .setNeedShowOADCaution(false);
                                Intent intent = new Intent(ACTION_ShowOAD);
                                sendBroadcast(intent);
                            }
                            Intent intent = new Intent(ACTION_UpdateOADState);
                            sendBroadcast(intent);
                        }
                    }

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        LogUtils.e(TAG, "A onFailure:" + arg1);
                    }
                });

        http.download(firmwareInfoB.fileURL, filePathB,
                new RequestCallBack<File>() {

                    @Override
                    public void onSuccess(ResponseInfo<File> responseInfo) {
                        // TODO Auto-generated method stub
                        LogUtils.e(
                                TAG,
                                "B responseInfo:"
                                        + responseInfo.result.getAbsolutePath());
                        successB = true;
                        mySharedPreferences.saveImageBFilePath(filePathB);
                        if (successA && successB) {

                            if (mySharedPreferences.getNeedShowOADCaution()) {
                                mySharedPreferences
                                        .setNeedShowOADCaution(false);
                                Intent intent = new Intent(ACTION_ShowOAD);
                                sendBroadcast(intent);
                            }
                            Intent intent = new Intent(ACTION_UpdateOADState);
                            sendBroadcast(intent);
                        }
                    }

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        LogUtils.e(TAG, "B onFailure:" + arg1);
                    }
                });

    }

    @Override
    public void onKeyValueSendSuccess(int tag, byte[] value,
                                      BluetoothDevice device) {
        Log.i("tag", "发送成功  value:" + Util.Bytes2HexString(value));
    }

    @Override
    public void onGetOADProgress(int tag, float progress, int secondLeft) {
        // TODO Auto-generated method stub
        Log.e(TAG, " onGetOADProgress:" + progress + "  secondLeft:"
                + secondLeft);

        Intent intent = new Intent(ACTION_OADProgress);
        intent.putExtra(EXTRA_OADProgress, progress);
        intent.putExtra(EXTRA_OADTimeLeft, secondLeft);
        sendBroadcast(intent);


    }

    @Override
    public void onGetKeyValue(int tag, byte[] value, BluetoothDevice device) {
        // TODO Auto-generated method stub
        Log.e("tag",
                "onGetKeyValue device" + tag + "  value:"
                        + Util.Bytes2HexString(value));
        switch (value[0]) {
            case 0x07:
                switch (value[1]) {
                    case 0x04:
                        // 验证用户结果
                        switch (value[3]) {
                            case 0x01: {
                                // 成功
                                application.swDevicesList.get(tag).checkUserOk = true;
                                Log.e("tag", " read battery 1");
                                handler.postDelayed(batteryReadRunnable, 5 * 1000);
                                startSendSettings(tag);
                                String address = device.getAddress().replace(":", "")
                                        .toUpperCase();
                                checkNeedBindDevice(address);
                                break;
                            }
                            case 0x00:
                                // 失败
                                switch (value[value.length - 1]) {
                                    case 0x00:
                                        // 空用户,要跳转到用户界面，并弹出输入管理密码（管理密码默认6个8）
                                        Log.e("tag",
                                                "phonenum:" + mySharedPreferences.getPhoneNum());

                                        LogUtils.e(TAG, " 空用户,要跳转到用户界面，并弹出输入管理密码（管理密码默认6个8）");

                                        Intent intent = new Intent(ACTION_FIST_ADDUSER);
                                        sendBroadcast(intent);
                                        // new Thread(new Runnable() {
                                        //
                                        // @Override
                                        // public void run() {
                                        // try {
                                        // //不加延迟命令发出去，硬件接收不到
                                        // Thread.sleep(500);
                                        // } catch (InterruptedException e) {
                                        // // TODO Auto-generated catch block
                                        // e.printStackTrace();
                                        // }
                                        // application.swDevicesList.get(0).sendAddUserPhone(mySharedPreferences.getPhoneNum());
                                        // }
                                        // }).start();
                                        String address = device.getAddress().replace(":", "")
                                                .toUpperCase();
                                        checkNeedBindDevice(address);
                                        break;
                                    case 0x01:
                                        // 验证失败
                                        String address1 = device.getAddress().replace(":", "")
                                                .toUpperCase();
                                        checkNeedBindDevice(address1);
                                        sendBroadcast(new Intent(ACTION_CHECKUSER_RESULT));
                                        break;
                                    default:
                                        break;
                                }

                                break;

                            default:
                                break;
                        }
                        break;
                    case 0x05:
                        // 添加普通用户列表返回值
                        Intent intent_5 = null;
                        switch (value[3]) {
                            case 0x00:
                                // 失败
                                intent_5 = new Intent(ACTION_ADD_USER_RESULT);
                                intent_5.putExtra(VALUE_INFO, 0);
                                sendBroadcast(intent_5);

                                LogUtils.e(TAG, "  ACTION_ADD_USER_RESULT  1111");
                                break;
                            case 0x01:
                                // 成功
                                intent_5 = new Intent(ACTION_ADD_USER_RESULT);
                                LogUtils.e(TAG, "  ACTION_ADD_USER_RESULT  2222");
                                intent_5.putExtra(VALUE_INFO, 1);
                                sendBroadcast(intent_5);
                                if (!application.swDevicesList.get(tag).checkUserOk) {
                                    application.swDevicesList.get(tag).checkUserOk = true;
                                    handler.removeCallbacks(batteryReadRunnable);
                                    handler.postDelayed(batteryReadRunnable, 5 * 1000);
                                    startSendSettings(tag);
                                }

                                break;
                            default:
                                break;
                        }
                        break;
                    case 0x06:
                        // 删除普通用户列表返回值
                        Intent intent_6 = null;
                        switch (value[3]) {
                            case 0x00:
                                // 失败
                                intent_6 = new Intent(ACTION_DELETE_USER_RESULT);
                                intent_6.putExtra(VALUE_INFO, 0);
                                sendBroadcast(intent_6);
                                break;
                            case 0x01:
                                // 成功
                                intent_6 = new Intent(ACTION_DELETE_USER_RESULT);
                                intent_6.putExtra(VALUE_INFO, 1);
                                sendBroadcast(intent_6);
                                break;
                            default:
                                break;
                        }
                        break;
                    case 0x07:
                        // 查询普通用户列表返回值
                        switch (value[3]) {
                            case 0x00:
                                // 失败
                                Log.e(TAG, " sendCheckOutAllUser 2222  ");
                                application.swDevicesList.get(tag).sendCheckOutAllUser();
                                application.swDevicesList.get(tag).userInfos.clear();
                                break;
                            case 0x01:
                                // 成功
                                application.swDevicesList.get(tag).userLength = value[value.length - 1];
                                application.swDevicesList.get(tag).userInfos.clear();
                                break;
                            default:
                                break;
                        }
                        break;
                    case 0x08:
                        // 用户授权结果
                        if (value[2] == 0x04 && value[3] == 0x01) {
                            LogUtils.e(TAG, "授权验证成功");
                            // 授权验证成功
                            // 把该用户添加进去
                            application.swDevicesList.get(tag).sendAddUserPhone(
                                    mySharedPreferences.getPhoneNum());
                    /*startSendSettings(tag);
                    String address = device.getAddress().replace(":", "")
                            .toUpperCase();
                    checkNeedBindDevice(address);*/

                        } else if (value[2] == 0x05 && value[3] == 0x00) {
                            final int error = value[4];
                            handler.post(new Runnable() {

                                @Override
                                public void run() {
                                    // TODO Auto-generated method stub
                                    if (error == 1) {
                                        LogUtils.e(TAG, "用户授权验证失败： 无用户");
                                        ToastUtils.showToast(MyService.this,
                                                "用户授权验证失败： 无用户", 2000);
                                    } else if (error == 2) {
                                        LogUtils.e(TAG, "用户授权验证失败： 有用户，仅MAC地址错误");
                                        ToastUtils.showToast(MyService.this,
                                                "用户授权验证失败： 有用户，仅MAC地址错误", 2000);
                                    } else if (error == 3) {
                                        LogUtils.e(TAG, "用户授权验证失败： 有用户，仅授权密码错误");
                                        ToastUtils.showToast(MyService.this,
                                                "用户授权验证失败： 有用户，仅授权密码错误", 2000);
                                    } else if (error == 4) {
                                        LogUtils.e(TAG, "用户授权验证失败： 有用户，验证全错误");
                                        ToastUtils.showToast(MyService.this,
                                                "用户授权验证失败： 有用户，验证全错误", 2000);
                                    }
                                }
                            });

                        }

                        break;
                    case 0x12: {
                        // 验证管理员密码结果
                        Log.e("tag", "验证管理员密码结果:" + value[value.length - 1]);
                        Intent intent = null;
                        switch (value[value.length - 1]) {
                            case 0x00:
                                // 失败
                                intent = new Intent(ACTION_CHECKADMINEPWD_RESULT);
                                intent.putExtra(VALUE_INFO, 0);
                                sendBroadcast(intent);
                                break;
                            case 0x01:
                                // 成功
                                intent = new Intent(ACTION_CHECKADMINEPWD_RESULT);
                                intent.putExtra(VALUE_INFO, 1);
                                sendBroadcast(intent);
                                mySharedPreferences.savaBoolen("needAddFirstUser",false);
                                break;
                        }
                    }
                    break;
                    case 0x13:
                        // 管理员密码更改命令
                        Intent intent_t = null;
                        switch (value[value.length - 1]) {
                            case 0x00:
                                // 失败
                                intent_t = new Intent(ACTION_ADMINEPWD_UPDATE_RESULT);
                                intent_t.putExtra(VALUE_INFO, 0);
                                sendBroadcast(intent_t);
                                break;
                            case 0x01:
                                // 成功
                                intent_t = new Intent(ACTION_ADMINEPWD_UPDATE_RESULT);
                                intent_t.putExtra(VALUE_INFO, 1);
                                sendBroadcast(intent_t);
                                break;
                        }
                        break;

                    case 0x14:
                        // 解锁命令回复

                        if (value.length == 4 && value[3] == 1) {
                            // 解锁成功
                            handler.post(new Runnable() {

                                @Override
                                public void run() {
                                    // TODO Auto-generated method stub
                                    ToastUtils.showToast(MyService.this,
                                            getString(R.string.unlock_success), 1000);
                                }
                            });
                        } else {
                            // 解锁失败
                            handler.post(new Runnable() {

                                @Override
                                public void run() {
                                    // TODO Auto-generated method stub
                                    ToastUtils.showToast(MyService.this,
                                            getString(R.string.unlock_fail), 1000);
                                }
                            });
                        }

                        break;

                    case 0x15: {
                        // 查询到开锁记录
                        if (value.length >= 4 && value[3] == 1) {
                            if (value.length == 13) {
                                String timeStr = Conversion.Bytes2HexString(Conversion
                                        .subByteArray(value, 8, 5));
                                LogUtils.e(TAG, " timeStr:" + timeStr);
                                // 0x46对应的 ascII "F"
                                // 0x42对应的 ascII "B"

                                int type = value[5];
                                int year = Integer.valueOf(timeStr.substring(0, 2));

                                year = 2000 + year;

                                int month = Integer.valueOf(timeStr.substring(2, 4));
                                int day = Integer.valueOf(timeStr.substring(4, 6));
                                int hour = Integer.valueOf(timeStr.substring(6, 8));
                                int minute = Integer.valueOf(timeStr.substring(8, 10));
                                // int second = Integer.valueOf(timeStr.substring(10,
                                // 12));

                                String address = device.getAddress().replace(":", "")
                                        .toUpperCase();

                                OpenLockInfo openLockInfo = new OpenLockInfo();
                                openLockInfo.setStyle(Integer.valueOf(type));
                                openLockInfo.setAddress(getString(R.string.no_address));
                                openLockInfo.setMacAddress(address);
                                String formatTime = String.format(
                                        "%d%s%02d%s%02d%s %02d:%02d", year,
                                        getString(R.string.year), month,
                                        getString(R.string.month), day,
                                        getString(R.string.day), hour, minute);
                                LogUtils.e(TAG, "formatTime:" + formatTime);
                                openLockInfo.setTime(formatTime);

                                ArrayList<OpenLockInfo> lockInfos = new ArrayList<OpenLockInfo>();
                                lockInfos.add(openLockInfo);

                                Intent intent = new Intent(ACTION_Get_OpenLockInfo);
                                intent.putExtra(Extra_OpenLockInfo, lockInfos);
                                sendBroadcast(intent);
                            }
                        }

                    }
                    break;
                    case 0x16: {// 注册指纹响应

                        if (value[3] == 1) {
                            // 注册指令响应成功
                            Intent intent = new Intent(
                                    AddFringerActivity.Action_RegisterStartedSuccess);
                            sendBroadcast(intent);
                        } else if (value[3] == 0) {
                            // 注册指令响应失败
                            Intent intent = new Intent(
                                    AddFringerActivity.Action_RegisterFailed);
                            sendBroadcast(intent);
                        } else if (value[3] == 0x56) {
                            // 第一次指纹录入返回
                            Intent intent = new Intent(
                                    AddFringerActivity.Action_Step_1_Complete);
                            sendBroadcast(intent);
                        } else if (value[3] == 0x57) {
                            // 第二次指纹录入返回
                            Intent intent = new Intent(
                                    AddFringerActivity.Action_Step_2_Complete);
                            sendBroadcast(intent);
                        } else if (value[3] == 0x58) {
                            // 第三次指纹录入返回
                            if (value[4] == 1) {
                                // 成功
                                int id = Conversion.buildUint16(value[6], value[7]);

                                Intent intent = new Intent(
                                        AddFringerActivity.Action_Step_3_Complete);
                                intent.putExtra(AddFringerActivity.Extra_ID, id);
                                sendBroadcast(intent);

                            } else {
                                // 失败
                                Intent intent = new Intent(
                                        AddFringerActivity.Action_RegisterFailed);
                                sendBroadcast(intent);
                            }
                        }
                    }

                    break;

                    default:
                        break;
                }
                break;
            case 0x08:
                switch (value[1]) {
                    case 0x02:
                        // 用户列表上传

                        Log.e(TAG, " 用户列表上传  ");
                        int index = value[3];

                        StringBuffer buffer = new StringBuffer();

                        byte[] bs = new byte[value.length - 4];
                        for (int i = 4, j = 0; i < value.length; i++, j++) {
                            int n = value[i] - 48;
                            buffer.append(n + "");
                            ;
                        }
                        String phoneNum = buffer.toString();
                        Log.e("tag", "phoneNum:" + phoneNum);
                        UserInfo userInfo = new UserInfo();
                        userInfo.setChild_phonenum(phoneNum);
                        application.swDevicesList.get(0).userInfos.add(userInfo);

                        if (index == application.swDevicesList.get(0).userLength) {

                            if (application.swDevicesList.get(0).userInfos.size() == index) {
                                Intent intent = new Intent(ACTION_CHECK_ALLUSER_RESULT);
                                sendBroadcast(intent);
                            } else {
                                application.swDevicesList.get(0).userInfos.clear();
                                application.swDevicesList.get(0).userLength = 0;
                                Log.e(TAG, " sendCheckOutAllUser 111111  ");
                                application.swDevicesList.get(0).sendCheckOutAllUser();
                            }
                        }
                        break;

                    default:
                        break;
                }

                break;
            default:
                break;
        }

    }


    private void checkNeedBindDevice(String address) {
        DeviceInfo deviceInfo = dataBaseUtil.loadDeviceInfoByMac(
                mySharedPreferences.getPhoneNum(), address);

        LogUtils.e(TAG, "  bindDevice 000000");
        if (deviceInfo == null) {
            LogUtils.e(TAG, "  bindDevice 111111");
            DeviceInfo deInfo = new DeviceInfo();
            deInfo.setMac(address);
            deInfo.setPhoneNum(mySharedPreferences.getPhoneNum());
            dataBaseUtil.saveDeviceInfo(deInfo);

            Intent intent2 = new Intent(ACTION_MAIN_DEVICEUI_CHANGE);
            sendBroadcast(intent2);

            final String mAddress = address;
            handler.post(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    bindDevice(mAddress);
                }
            });

        }
    }

    private void checkWain(final int tag) {

        application.swDevicesList.get(tag).isChecking = true;
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Thread.sleep(5 * 1000);
                    if (!application.swDevicesList.get(tag).isConnected()) {
                        // 添加提醒
                        RemindInfo info = new RemindInfo();
                        info.setMacAddress(mySharedPreferences.getBluAdress());
                        info.setStyle(2);
                        info.setUpflag(1);
                        info.setTime(Util.formatTimeStyle_4(System
                                .currentTimeMillis()));
                        info.setLat(Latitude);
                        info.setLng(Longitude);
                        info.setAddress(mapAddress);
                        info.setUser_id(mySharedPreferences.getUserId());
                        dataBaseUtil.saveRemindInfo(info);

                        Intent intent = new Intent(ACTION_DISCONNECTED);
                        intent.putExtra(SELECT_TAG, tag);
                        sendBroadcast(intent);

                        if (!mySharedPreferences.getDisturbWainAction()) {
                           /* MusicInfo musicInfo = null;
                            String path = "android.resource://" + getPackageName()
                                    + "/" + R.raw.lost;
                            musicInfo = new MusicInfo(path);
                            MusicPlayer  musicPlayer=new MusicPlayer(MyService.this);
                            musicPlayer.playWithPath(path);*/
                            application.swDevicesList.get(tag).musicPlayer.playWithTimesAndPath(
                                    mySharedPreferences
                                            .getLostDeviceWainTimes(),
                                    mySharedPreferences.getLostDeviceWainVoicePath(),
                                    true, false);
                        }
                    }
                    application.swDevicesList.get(tag).isChecking = false;

                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }

        ).start();
    }

    private List<Thread> sendSettingThreadList = new ArrayList<Thread>();
    private static int INTERVAL = 150;

    private void startSendSettings(final int tag) {
        stopSendSettings(tag);

        Log.e(TAG, "------startSendSettings-------");
        sendSettingThreadList.set(tag, new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    // 读版本
                    application.swDevicesList.get(tag).getImageVerAndType();
                    handler.postDelayed(checkVersionCodeRunnable, 3000);

                    Thread.sleep(INTERVAL);

                    application.swDevicesList.get(tag).readDeviceName();
                    handler.postDelayed(checkVersionNameRunnable, 4000);
                    Thread.sleep(INTERVAL);

                    // 读电量
                    application.swDevicesList.get(tag).readBattery();
                    Thread.sleep(INTERVAL);
                    //
                    application.swDevicesList.get(tag).sendRTC();
                    Thread.sleep(INTERVAL);
                    // 设备报警距离
                    int distanceType = mySharedPreferences
                            .getDeviceRingFarNearAction();
                    if (distanceType == 0) {
                        LogUtils.e(TAG, "  SETTING_DISTANCE_NEAR ");
                        application.swDevicesList.get(tag).setAlertDistance(
                                SWDevice.SETTING_DISTANCE_NEAR);
                    } else if (distanceType == 1) {
                        LogUtils.e(TAG, "  SETTING_DISTANCE_MID ");
                        application.swDevicesList.get(tag).setAlertDistance(
                                SWDevice.SETTING_DISTANCE_MID);
                    } else if (distanceType == 2) {
                        LogUtils.e(TAG, "  SETTING_DISTANCE_FAR ");
                        application.swDevicesList.get(tag).setAlertDistance(
                                SWDevice.SETTING_DISTANCE_FAR);
                    }
                    Thread.sleep(INTERVAL);

                    // 报警使能
                    if (mySharedPreferences.getDisturbWainAction()) {
                        application.swDevicesList.get(tag).stopAntilost();
                    } else {
                        application.swDevicesList.get(tag).startAntilost();
                    }

                    Thread.sleep(INTERVAL);

                    application.swDevicesList.get(tag).sendToDevice(98);// SETTING_NOT_DISTURB_OFF
                    // = 98;
                    Thread.sleep(INTERVAL);

                    application.swDevicesList.get(tag).sendToDevice(96);// SETTING_InterimNotDisturb_OFF
                    // = 96;
                    Thread.sleep(INTERVAL);

                    // 减少误报
                    if (mySharedPreferences.getReduceFalsePositives()) {
                        application.swDevicesList.get(tag)
                                .startReduceUnexpectedWarning();

                    } else {
                        application.swDevicesList.get(tag)
                                .stopReduceUnexpectedWarning();

                    }

                    Thread.sleep(INTERVAL);
                    // 设备报警模式
                    int ringType = mySharedPreferences.getDeviceRingType();
                    if (ringType == 0) {
                        application.swDevicesList.get(tag).sendToDevice(
                                SWDevice.SETTING_ALERT_MODE_RING);

                    } else if (ringType == 1) {
                        application.swDevicesList.get(tag).sendToDevice(
                                SWDevice.SETTING_ALERT_MODE_VIBRATE);

                    } else {
                        application.swDevicesList.get(tag).sendToDevice(
                                SWDevice.SETTING_ALERT_MODE_BOTH);

                    }
                    Thread.sleep(INTERVAL);
                    // 设备防丢报警次数
                    int ringTimes = mySharedPreferences
                            .getLostDeviceWainTimes();
                    if (ringTimes == 1) {
                        application.swDevicesList.get(tag).sendToDevice(
                                SWDevice.SETTING_DEVICE_ALERT_TINES_1);
                    } else if (ringTimes == 3) {
                        application.swDevicesList.get(tag).sendToDevice(
                                SWDevice.SETTING_DEVICE_ALERT_TINES_3);
                    } else {
                        application.swDevicesList.get(tag).sendToDevice(
                                SWDevice.SETTING_DEVICE_ALERT_TINES_5);
                    }
                    Thread.sleep(INTERVAL);
                    application.swDevicesList.get(tag).sendLockTimeMode(
                            mySharedPreferences.getDeviceLockTimes());

                    Thread.sleep(INTERVAL);

                    if (mySharedPreferences.getLowBatteryWain()) {
                        application.swDevicesList.get(tag).sendToDevice(11);
                    } else {
                        application.swDevicesList.get(tag).sendToDevice(10);
                    }

                    Thread.sleep(INTERVAL);

                    application.swDevicesList.get(tag).sendToDevice(9);

                    Thread.sleep(INTERVAL);
                    Thread.sleep(INTERVAL);
                    Thread.sleep(INTERVAL);
                    // 报警使能
                    application.swDevicesList.get(tag).sendToDevice(6);

                    Thread.sleep(INTERVAL);
                } catch (InterruptedException e) {
                    LogUtils.e(TAG,
                            "!!!!!!!!!  InterruptedException !!!!!!!!!!!!!!!111111 ");
                }
            }
        }));
        sendSettingThreadList.get(tag).start();
    }

    private Runnable checkVersionNameRunnable = new Runnable() {

        @Override
        public void run() {
            if (application.swDevicesList.get(0).isConnected()
                    && application.swDevicesList.get(0).versionName.equals("")) {
                application.swDevicesList.get(0).readDeviceName();
                handler.postDelayed(this, 3000);
            }

        }
    };

    private Runnable checkVersionCodeRunnable = new Runnable() {

        @Override
        public void run() {
            if (application.swDevicesList.get(0).isConnected()
                    && application.swDevicesList.get(0).versionCode == 0) {
                application.swDevicesList.get(0).getImageVerAndType();
                handler.postDelayed(this, 3000);
            }

        }
    };

    public void stopSendSettings(final int tag) {
        if (sendSettingThreadList.get(tag) != null) {// 停止发送配置
            sendSettingThreadList.get(tag).interrupt();

            handler.removeCallbacks(checkVersionCodeRunnable);
            handler.removeCallbacks(checkVersionNameRunnable);
        }
    }

    private void initRunnables() {

        for (int i = 0; i < 3; i++) {
            Thread thread = null;
            sendSettingThreadList.add(thread);
        }

    }

    Handler handler = new Handler();

    /**
     * 读电量
     */
    int battery_invalue = 10 * 60 * 1000;
    Runnable batteryReadRunnable = new Runnable() {

        @Override
        public void run() {
            if (application.swDevicesList.get(0).isConnected()
                    && !application.swDevicesList.get(0).isProgramming()) {
                application.swDevicesList.get(0).readBattery();
                Log.e("tag", "batteryReadRunnable ");
            }
            handler.postDelayed(batteryReadRunnable, battery_invalue);
        }
    };

    String action = "";
    private BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            action = intent.getAction();
            if (action.equals(ACTION_MYSERVICE)) {
                int value = intent.getIntExtra(VALUE_TAG, -1);
                switch (value) {
                    case 1:
                        // connect
                        if (MyConfig.bluetoothEnabled) {
                            if (!mySharedPreferences.getBluAdress().equals("")) {
                                scanManager.startScan();
                            } else {
                                scanManager.stopScan();
                            }
                        }

                        break;
                    case 2:
                        // disconnect

                        break;

                    case 3:
                        // remove
                        int tag = intent.getIntExtra(SELECT_TAG, -1);
                        if (tag >= 0 && tag < 3) {
                            Log.e("tag", "myservice remove :3");
                            application.swDevicesList.get(tag).remove();
                        }

                        break;
                    case 4:

                        break;
                    case 5:
                        //

                        break;

                    default:
                        break;
                }
            } else if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
                if (!MyConfig.canUse) {
                    return;
                }
                MyConfig.bluetoothEnabled = bluetoothAdapter.isEnabled();

                Intent intentBlu = new Intent(ACTION_BLUTOOTH_CHANGE);
                sendBroadcast(intentBlu);

                boolean bluflag = false;
                if (!mySharedPreferences.getBluAdress().equals("")) {
                    bluflag = true;
                }
                if (!bluflag) {// no device
                    return;
                }
                if (MyConfig.bluetoothEnabled) {// 蓝牙打开,connect
                    Log.e("tag", "蓝牙打开:");
                    scanManager.startScan();

                } else {// 蓝牙断开
                    Log.e("tag", "蓝牙断开:");
                    for (int i = 0; i < 1; i++) {
                        if (application.swDevicesList.get(i)
                                .getBluetoothDevice() != null) {
                            stopSendSettings(i);
                            Intent intentDisconnect = new Intent(
                                    ACTION_DISCONNECTED);
                            intentDisconnect.putExtra(SELECT_TAG, i);
                            sendBroadcast(intentDisconnect);
                            Log.i("tag", "断开线程：" + i);

                        }
                    }

                }
            } else if (action.equals(CONNECTIVITY_CHANGE_ACTION)) {
                Log.e("tag", "有网或没网：" + Util.hasNetwork(MyService.this));
                if (Util.hasNetwork(MyService.this)) {

                }
            }
        }
    };

    SwDeviceNew deviceNew;

    private void doValue(int value, final int select) {

        Log.i("tag", "value:" + value + "select:" + select);
        deviceNew = application.swDevicesList.get(select);
        if (value == 11) {

            // ringManager.onPopulateValue(10, select);
            // application.swDevicesList.get(select).lastStatus =
            // application.swDevicesList
            // .get(select).getDeviceStatus();
            // Log.e("tag", "hehe 设备寻找手机");
            // ringManager.onPopulateValue(value, select);
            // application.swDevicesList.get(select).setDeviceStatus(4);
            //
            // Intent intent = new
            // Intent(HomeActivityNew.ACTION_HomeActivity);// 4
            // // device
            // // ring
            // // 手机状态
            // intent.putExtra("connectFlag", select);
            // intent.putExtra("value", 6);
            // sendBroadcast(intent);
            //
            // String str = list_preferences.get(select).getNewDeviceName();
            // String string = String.format(getText(R.string.find_smartphone)
            // .toString(), (Object) str);
            // SKNotificationManager.showNotification(this, string, string,
            // SwDeviceNew.COMMAND_FINDING_PHONE, true,
            // deviceNew.notificationId_find_phone);

        } else if (value == 10) {// 取消ring
            // ringManager.onPopulateValue(value, select);
            // if (application.swDevicesList.get(select).getDeviceStatus() != 4)
            // {
            // return;
            // }
            // for (int i = 0; i < 5; i++) {
            // if (application.swDevicesList.get(i).getDeviceStatus() == 4) {
            // application.swDevicesList.get(i).setDeviceStatus(
            // application.swDevicesList.get(i).lastStatus);
            // }
            // }
            //
            // Intent intent = new
            // Intent(HomeActivityNew.ACTION_HomeActivity);// 4
            // // device
            // // ring
            // // 手机状态
            // intent.putExtra("connectFlag", select);
            // intent.putExtra("value", 7);
            // sendBroadcast(intent);

        } else if (value == 30) {// 钱包打开
            // if (allowOpen) {
            // ringManager.onPopulateValue(value);
            // MyNotificationManager.showNotification(this, value, true);
            // MyStatics.startLocateService(MyBleService.this, 2);
            // }
            // 44444444444444444444444444444444444444444444444444444444
        } else if (value == 20) { /* 停止手机报警 */
            // ringManager.stopSound();
        } else if (value == 21) {/* 要求手机报警 */

            // if (mySharedPreferences.getRingFlag()
            // && application.swDevicesList.get(select).isAllow) {
            //
            // if (isAllow_disturb && isAllow_interimdisturb) {
            // String str = list_preferences.get(select)
            // .getNewDeviceName();
            // String string = String.format(getText(R.string.out_range)
            // .toString(), (Object) str);
            // SKNotificationManager.showNotification(this, string,
            // string, SwDeviceNew.COMMAND_START_ALARM, true,
            // deviceNew.notificationId_start_alarm);
            // if (list_preferences.get(select).getWarningType() == 2) {
            // ringManager.onPopulateValue(value, select);
            // } else {
            // if (application.swDevicesList.get(select).phone_shake_ison) {
            // shakeManager.startUpdateListener();
            // }
            // application.swDevicesList.get(select).musicPlayer
            // .playWithTimesAndPath(
            // list_preferences.get(select)
            // .getPhoneRingTimes(),
            // list_preferences.get(select)
            // .getAntiLossVoicePath(),
            // list_preferences.get(select)
            // .getWarningType() != 0,
            // list_preferences.get(select)
            // .getPhoneVolume());
            // }
            //
            // }
            // list_preferences.get(select).saveRingFlag(false);
            // }
        } else if (value == 71 || value == 0x71) { /* 低电量报警 */
            RemindInfo info = new RemindInfo();
            info.setMacAddress(mySharedPreferences.getBluAdress());
            info.setStyle(3);
            info.setUpflag(1);
            info.setTime(Util.formatTimeStyle_4(System.currentTimeMillis()));
            info.setUser_id(mySharedPreferences.getUserId());
            dataBaseUtil.saveRemindInfo(info);
            Intent intent = new Intent(ACTION_LOW_BATTERYVALUE);
            intent.putExtra(SELECT_TAG, select);
            sendBroadcast(intent);

            if (mySharedPreferences.getLowBatteryWain()) {

                application.swDevicesList.get(select).musicPlayer
                        .playWithTimesAndPath(mySharedPreferences
                                        .getLowBatteryWainTimes(), mySharedPreferences
                                        .getLowBatteryWainVoicePath(),
                                mySharedPreferences.getLowBatteryVibrate(),
                                true);
            }
        } else if (value == 72 || value == 0x72) {/* 0电量 */
            RemindInfo info = new RemindInfo();
            info.setMacAddress(mySharedPreferences.getBluAdress());
            info.setStyle(3);
            info.setUpflag(1);
            info.setTime(Util.formatTimeStyle_4(System.currentTimeMillis()));
            info.setUser_id(mySharedPreferences.getUserId());
            dataBaseUtil.saveRemindInfo(info);
            Intent intent = new Intent(ACTION_LOW_BATTERYVALUE);
            intent.putExtra(SELECT_TAG, select);
            sendBroadcast(intent);

            if (mySharedPreferences.getLowBatteryWain()) {
                application.swDevicesList.get(select).musicPlayer
                        .playWithTimesAndPath(mySharedPreferences
                                        .getLowBatteryWainTimes(), mySharedPreferences
                                        .getLowBatteryWainVoicePath(),
                                mySharedPreferences.getLowBatteryVibrate(),
                                true);
            }
        } else if (value == 73) {/* 充电满 */
            // if (!mySharedPreferences.getDisturbWainAction()) {
            // ringManager.onPopulateValue(value, select);
            // String str = list_preferences.get(select).getNewDeviceName();
            // String string = String.format(getText(R.string.power_full)
            // .toString(), (Object) str);
            // SKNotificationManager.showNotification(this, string, string,
            // SwDeviceNew.COMMAND_FULL_BATTERY, true,
            // deviceNew.notificationId_power);
            // }
        } else if (value == 60) { /* 连接有效，允许下次报警 */

        } else if (value == 88) { // 行李到达
            // if (list_preferences.get(select).getIsLuggage()) {
            // ringManager.onPopulateValue(88, select);
            // String str = list_preferences.get(select).getNewDeviceName();
            // String string = String.format(
            // getText(R.string.luggage_iscoming).toString(),
            // (Object) str);
            // SKNotificationManager.showNotification(this, string, string,
            // 88, true, deviceNew.notificationId_go_wain);
            // // MyNotificationManager.showNotification(this, value,str,
            // // true);
            // list_preferences.get(select).saveIsLuggage(false);
            // }
        } else if (value == 9) {// 提醒更新免打扰

        } else if (value == 7) {// 进入近距离报警监控状态，每3秒收到一次数据然后下发一次OK，一旦收不到就报警
            // 为了解决三星平台断开TimerOut时间为20S问题 已失效

        } else if (value == 8) {// 取消模式
            // toast("收到8，近距离检测模式取消，"); 已失效

        } else if (value == 6) {// 1分钟存在提醒，已便于程序不被杀死
            // sendToDevice(UUIDUtils.Write_Char_UUID_2A08, (byte) 2);// 回复ACK

        }
    }

    /**
     * 绑定设备
     */
    void bindDevice(final String str) {
        if (!Util.hasNetwork(MyService.this)) {
            return;
        }
        LogUtils.e(TAG, "  bindDevice 22222");
        ComyouHttpProgram httpProgram = new ComyouHttpProgram();
        //httpProgram.add("phoneNum", mySharedPreferences.getPhoneNum());
        httpProgram.add("user_id", mySharedPreferences.getUserId() + "");

        httpProgram.add("mac", str);
        ComyouHttpClient httpClient = new ComyouHttpClient(MyConfig.IP
                + "app/Login/bind_list");
        httpClient.postAsync(httpProgram, new ComyouHttpCallBack() {

            @Override
            public void onResponse(final String string) {
                Log.e("tag", "1 bindDevice=============" + string);

//				handler.post(new Runnable() {
//					
//					@Override
//					public void run() {
//						// TODO Auto-generated method stub
//						ToastUtils.showToast(MyService.this, "1 bind_success=============" + string, 3000);
//					}
//				});


                try {
                    JSONObject jsonObject = new JSONObject(string);
                    int err = jsonObject.getInt("err");
                    if (err == 0) {
//						JSONObject dataObject = jsonObject
//								.getJSONObject("data");


                    }

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String arg0, IOException arg1) {
                // TODO Auto-generated method stub
                LogUtils.e(TAG, "  bindDevice 44444");
            }
        });

    }

    Runnable upRemindInfoRunnable = new Runnable() {

        @Override
        public void run() {
            List<RemindInfo> remindInfos = dataBaseUtil.loadRemindInfoByUpflag(
                    mySharedPreferences.getUserId(), 1);
            if (Util.hasNetwork(MyService.this) && remindInfos != null
                    && remindInfos.size() > 0) {
                for (int i = 0; i < remindInfos.size(); i++) {
                    RemindInfo remindInfo = remindInfos.get(i);
                    upRemindInfo(remindInfo);
                }

            }
            handler.postDelayed(this, TIME_INTERVAL);

        }
    };

    /**
     * 上传智能提醒信息
     */
    void upRemindInfo(final RemindInfo remindInfo) {
        ComyouHttpProgram httpProgram = new ComyouHttpProgram();
        httpProgram.add("user_id", mySharedPreferences.getUserId() + "");
        httpProgram.add("alert_style", remindInfo.getStyle() + "");
        httpProgram.add("x_coordinate", remindInfo.getLat() + "");
        httpProgram.add("y_coordinate", remindInfo.getLng() + "");
        httpProgram.add("alert_address", remindInfo.getAddress() + "");
        httpProgram.add("alert_time", remindInfo.getTime());
        httpProgram.add("alert_mac_address", remindInfo.getMacAddress());

        ComyouHttpClient httpClient = new ComyouHttpClient(MyConfig.IP
                + "app/user/device_alert_insert");
        httpClient.postAsync(httpProgram, new ComyouHttpCallBack() {

            @Override
            public void onResponse(String string) {
                Log.e("tag", "3 bind_success=============" + string);
                try {
                    JSONObject jsonObject = new JSONObject(string);
                    int err = jsonObject.getInt("err");
                    if (err == 0) {
                        remindInfo.setUpflag(0);
                        JSONObject dataObject = jsonObject
                                .getJSONObject("data");
                        int remind_id = dataObject.getInt("id");
                        remindInfo.setRemind_id(remind_id);
                        dataBaseUtil.saveRemindInfo(remindInfo);
                    }

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String arg0, IOException arg1) {
                // TODO Auto-generated method stub

            }
        });

    }

    private int TIME_INTERVAL = 5 * 60 * 1000;// 间隔时间
    Runnable upOpenLockInfoRunnable = new Runnable() {

        @Override
        public void run() {
            List<OpenLockInfo> openLockInfos = dataBaseUtil
                    .loadOpenLockInfoByUpflag(mySharedPreferences.getUserId(),
                            1);
            if (Util.hasNetwork(MyService.this) && openLockInfos != null
                    && openLockInfos.size() > 0) {
                for (int i = 0; i < openLockInfos.size(); i++) {
                    OpenLockInfo openLockInfo = openLockInfos.get(i);
                    upOpenLockInfo(openLockInfo);
                }

            }
            handler.postDelayed(upOpenLockInfoRunnable, TIME_INTERVAL);

        }
    };

    /**
     * 上传开锁记录
     */
    void upOpenLockInfo(final OpenLockInfo openLockInfo) {
        ComyouHttpProgram httpProgram = new ComyouHttpProgram();
        httpProgram.add("user_id", mySharedPreferences.getUserId() + "");
        httpProgram.add("create_time", openLockInfo.getTime() + "");
        httpProgram.add("x_coordinate", openLockInfo.getLat() + "");
        httpProgram.add("y_coordinate", openLockInfo.getLng() + "");
        httpProgram.add("lock_style", openLockInfo.getAddress());
        httpProgram.add("lock_address", openLockInfo.getAddress());
        httpProgram.add("mac_address", openLockInfo.getMacAddress());

        ComyouHttpClient httpClient = new ComyouHttpClient(MyConfig.IP
                + "app/user/lock_log_insert");
        httpClient.postAsync(httpProgram, new ComyouHttpCallBack() {

            @Override
            public void onResponse(String string) {
                Log.e("tag", "4 bind_success=============" + string);
                try {
                    JSONObject jsonObject = new JSONObject(string);
                    int err = jsonObject.getInt("err");
                    if (err == 0) {
                        openLockInfo.setUpflag(0);
                        JSONObject dataObject = jsonObject
                                .getJSONObject("data");
                        int lock_id = dataObject.getInt("id");
                        openLockInfo.setLock_id(lock_id);
                        dataBaseUtil.saveOpenLockInfo(openLockInfo);
                    }

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String arg0, IOException arg1) {
                // TODO Auto-generated method stub

            }
        });
    }

    Runnable deleteLockinfoRunnable = new Runnable() {

        @Override
        public void run() {
            List<OpenLockInfo> openLockInfos = dataBaseUtil
                    .loadOpenLockInfoByUpflag(mySharedPreferences.getUserId(),
                            2);
            if (Util.hasNetwork(MyService.this) && openLockInfos != null
                    && openLockInfos.size() > 0) {
                for (int i = 0; i < openLockInfos.size(); i++) {
                    OpenLockInfo openLockInfo = openLockInfos.get(i);
                    deleteOpenLockInfo(openLockInfo);
                }

            }
            handler.postDelayed(this, TIME_INTERVAL);
        }
    };

    /**
     * 删除开锁记录
     */
    void deleteOpenLockInfo(final OpenLockInfo openLockInfo) {
        ComyouHttpProgram httpProgram = new ComyouHttpProgram();
        httpProgram.add("id", openLockInfo.getLock_id() + "");
        httpProgram.add("table", MyConfig.Table_lock);
        ComyouHttpClient httpClient = new ComyouHttpClient(MyConfig.IP
                + "app/user/dele_excu");
        httpClient.postAsync(httpProgram, new ComyouHttpCallBack() {

            @Override
            public void onResponse(String string) {
                Log.e("tag", "5 bind_success=============" + string);
                try {
                    JSONObject jsonObject = new JSONObject(string);
                    int err = jsonObject.getInt("err");
                    if (err == 0) {
                        dataBaseUtil.deleteOpenLockInfo(openLockInfo);
                    }

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String arg0, IOException arg1) {
                // TODO Auto-generated method stub

            }
        });
    }

    Runnable deleteRemindInfoRunnable = new Runnable() {

        @Override
        public void run() {
            List<RemindInfo> remindInfos = dataBaseUtil.loadRemindInfoByUpflag(
                    mySharedPreferences.getUserId(), 2);
            if (Util.hasNetwork(MyService.this) && remindInfos != null
                    && remindInfos.size() > 0) {
                for (int i = 0; i < remindInfos.size(); i++) {
                    RemindInfo remindInfo = remindInfos.get(i);
                    deleteRemindInfo(remindInfo);
                }

            }
            handler.postDelayed(this, TIME_INTERVAL);

        }
    };

    /**
     * 删除开锁记录
     */
    void deleteRemindInfo(final RemindInfo remindInfo) {
        ComyouHttpProgram httpProgram = new ComyouHttpProgram();
        httpProgram.add("id", remindInfo.getRemind_id() + "");
        httpProgram.add("table", MyConfig.Table_alert);
        ComyouHttpClient httpClient = new ComyouHttpClient(MyConfig.IP
                + "app/user/dele_excu");
        httpClient.postAsync(httpProgram, new ComyouHttpCallBack() {

            @Override
            public void onResponse(String string) {
                Log.e("tag", "6 bind_success=============" + string);
                try {
                    JSONObject jsonObject = new JSONObject(string);
                    int err = jsonObject.getInt("err");
                    if (err == 0) {
                        dataBaseUtil.deleteRemindInfo(remindInfo.getId());
                    }

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String arg0, IOException arg1) {
                // TODO Auto-generated method stub

            }
        });
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub

        if (null != locationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
        if (wakeLock != null) {
            wakeLock.release();
            wakeLock = null;
        }

        if (MyConfig.bluetoothEnabled && application.swDevicesList != null
                && application.swDevicesList.size() > 0) {
            for (int i = 0; i < 3; i++) {
                application.swDevicesList.get(i).remove();
            }
        }

        Intent localIntent = new Intent();
        localIntent.setClass(this, MyService.class);
        this.startService(localIntent);
    }

}
